package org.swxjava.core;

import java.io.IOException;
import java.util.Calendar;
import java.util.TimeZone;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.swxjava.Container;
import org.swxjava.Marshaller;
import org.swxjava.Reply;
import org.swxjava.WebContext;
import org.swxjava.WebContextFactory;
import org.swxjava.assembler.ConverterManager;
import org.swxjava.assembler.MarshallException;
import org.swxjava.assembler.SwxAssembler;
import org.swxjava.assembler.SwxAssemblerConfig;

public abstract class AbstractSwxMarshaller implements Marshaller {

	public static final String SWX_FILE_NAME = "data.swf";
	
	protected SwxAssemblerConfig config;

	public void marshallOutbound(Reply reply, HttpServletRequest request,
			HttpServletResponse response) throws IOException, MarshallException {
		
		// setup compiler
		SwxAssembler assembler = getSwxAssembler(reply);
		assembler.setAllowDomain(config.isAllowDomain());
		assembler.setCompressionLevel(config.getCompressionLevel());
		
		// do compile swx
		byte[] swf = assembler.compile(reply.getReply());
		
		response.setContentType("application/x-shockwave-flash");
		response.setContentLength(swf.length);
		response.setHeader("Content-Disposition","attachment; filename=" + SWX_FILE_NAME);
		
		applyCacheHeader(response);

		ServletOutputStream os = response.getOutputStream();
		try {
			os.write(swf);
		} finally {
			os.close();
		}
	}
	
	private void applyCacheHeader(HttpServletResponse response) {
		// cache control
		Calendar cal = Calendar.getInstance();
		cal.setTimeZone(TimeZone.getTimeZone("GMT"));
		cal.set(1970,0,1,0,0,0);
		
		response.setDateHeader("Last-Modified", System.currentTimeMillis());
		response.setDateHeader("Expires", cal.getTime().getTime());
		response.addHeader("Cache-Control", "no-cache");
		//response.addHeader("Cache-Control", "no-store, no-cache, must-revalidate");
		//response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		
		// Could not apply Pragma,no-cache after IE5
		// http://support.microsoft.com/kb/q234067/
		response.addHeader("Pragma", "no-cache");
		
		//response.setHeader("Pragma", "");
		//response.setHeader("Cache-Control", "");
	}
	
	public void setSwxCompilerConfig(SwxAssemblerConfig config) {
		this.config = config;
	}

	protected SwxAssembler getSwxAssembler(Reply reply) {
		// Retrieve container
        WebContext webContext = WebContextFactory.get();
        Container container = webContext.getContainer();
        ConverterManager converterManager = container.getConverterManager();
        // Setup swx assembler
		SwxAssembler assembler = new SwxAssembler();
		assembler.setDebug(reply.isDebug());
		assembler.setUrl(reply.getUrl());
		assembler.setConverterManager(converterManager);
		return assembler;
	}

}
